/**
 * 
 */
package ro.vikingsoft.androidprj;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

/**
 * @author voicuad
 *
 */
public class TableQuestionsDAO {
	// Database fields
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	private String[] allColumns = { MySQLiteHelper.COLUMN_TEST_ID,
			MySQLiteHelper.COLUMN_TEST_TITLE };

	public TableQuestionsDAO(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}

	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}

	public void close() {
		dbHelper.close();
	}

	public TableQuestions createQuestion(String test) {
		ContentValues values = new ContentValues();
		values.put(MySQLiteHelper.COLUMN_QUESTIONS_TITLE, test);
		long insertId = database.insert(MySQLiteHelper.COLUMN_QUESTIONS_TITLE, null,	values);
		Cursor cursor = database.query(MySQLiteHelper.COLUMN_QUESTIONS_TITLE,
				allColumns, MySQLiteHelper.COLUMN_QUESTIONS_ID + " = " + insertId, null,
				null, null, null);
		cursor.moveToFirst();
		TableQuestions newQuestion = cursorToQuestion(cursor);
		cursor.close();
		return newQuestion;
	}

	public void deleteQuestion(TableQuestions question) {
		long id = question.getIdquestion();
		System.out.println("Question deleted with id: " + id);
		database.delete(MySQLiteHelper.TABLE_QUESTIONS, MySQLiteHelper.COLUMN_QUESTIONS_ID
				+ " = " + id, null);
	}

	public void deleteQuestionByTestId(int testID) {
		System.out.println("Questions deleted with test id: " + testID);
		database.delete(MySQLiteHelper.TABLE_QUESTIONS, MySQLiteHelper.COLUMN_TEST_ID
				+ " = " + testID, null);
	}
	
	public List<TableQuestions> getAllQuestions() {
		List<TableQuestions> questions = new ArrayList<TableQuestions>();

		Cursor cursor = database.query(MySQLiteHelper.TABLE_TESTS,
				allColumns, null, null, null, null, null);

		cursor.moveToFirst();
		while (!cursor.isAfterLast()) {
			TableQuestions question = cursorToQuestion(cursor);
			questions.add(question);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		return questions;
	}

	private TableQuestions cursorToQuestion(Cursor cursor) {
		TableQuestions question = new TableQuestions();
		question.setIdtest(cursor.getLong(0));
		question.setTitle(cursor.getString(1));
		return question;
	}
}
